package pers.xiaojun.boot.mybatis.core.query;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.springframework.util.StringUtils;

/**
 * 增加强 LambdaQueryWrapper 的功能
 *
 * @author xiaojun
 * @since 2025-11-02
 */
public class LambdaQueryWrapperX<T> extends LambdaQueryWrapper<T> {

    /**
     * 增强 like：当值非空才进行判断
     *
     * @param column 字段
     * @param val    值
     * @return LambdaQueryWrapperX
     */
    public LambdaQueryWrapperX<T> likeIfPresent(SFunction<T, ?> column, String val) {
        if (StringUtils.hasText(val)) {
            return (LambdaQueryWrapperX<T>) like(column, val);
        }
        return this;
    }

    /**
     * 增强 eq：当值非空才进行判断
     *
     * @param column 字段
     * @param val    值
     * @return LambdaQueryWrapperX
     */
    public LambdaQueryWrapperX<T> eqIfPresent(SFunction<T, ?> column, Object val) {
        if (ObjectUtil.isNotEmpty(val)) {
            return (LambdaQueryWrapperX<T>) eq(column, val);
        }
        return this;
    }

    /**
     * 增强 between：根据范围区间起始值是否缺失自动转为符合要求的条件<br>
     * 1.起始值为空时，转为 <= 结束值<br>
     * 2.结束值为空时，转为 >= 起始值<br>
     * 3.都为空时，不进行判断
     *
     * @param column 字段
     * @param val1   起始值
     * @param val2   结束值
     * @return LambdaQueryWrapperX
     */
    public LambdaQueryWrapperX<T> betweenIfPresent(SFunction<T, ?> column, Object val1, Object val2) {
        if (val1 != null && val2 != null) {
            return (LambdaQueryWrapperX<T>) between(column, val1, val2);
        }
        if (val1 != null) {
            return (LambdaQueryWrapperX<T>) ge(column, val1);
        }
        if (val2 != null) {
            return (LambdaQueryWrapperX<T>) le(column, val2);
        }
        return this;
    }

    /**
     * 增强 between：传递数组方式，根据数组情况自动处理
     *
     * @param column 字段
     * @param values 值数组
     * @return LambdaQueryWrapperX
     */
    public LambdaQueryWrapperX<T> betweenIfPresent(SFunction<T, ?> column, Object[] values) {
        Object val1 = ArrayUtil.get(values, 0);
        Object val2 = ArrayUtil.get(values, 1);
        return betweenIfPresent(column, val1, val2);
    }


}
